package com.browser.bookmark.controller;

import com.browser.bookmark.entity.*;
import com.browser.bookmark.maaper.UserMapper;
import com.browser.bookmark.service.IBookMarkService;
import com.browser.bookmark.service.IMenuService;
import com.browser.bookmark.service.IUserService;
import com.browser.bookmark.utils.Base64;
import com.browser.bookmark.utils.HtmlUtil;
import com.browser.bookmark.utils.JWTUtil;
import io.swagger.annotations.Api;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jsoup.HttpStatusException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.net.ssl.SSLHandshakeException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;



/**
 * @Auther: Wang
 * @Date: 2020/02/13 17:54
 * 功能描述: 导入书签 导出书签
 */
@Api(description = "导入书签 导出书签接口")
@Controller
@RequiresPermissions("user:show")
@RequestMapping("/IO")
public class BrowserController {
    public static Logger logger =  LoggerFactory.getLogger(BrowserController.class);
    @Autowired
    private IMenuService iMenuService;

    @Autowired
    private IBookMarkService iBookMarkService;
    @Autowired
    private IUserService iUserService;

    @RequestMapping("/import")
    public void importCollect(@RequestParam("htmlFile") MultipartFile htmlFile, String structure, String type){
        logger.debug("开始上传状态是:"+structure);
        String username = JWTUtil.getUsername((String) SecurityUtils.getSubject().getPrincipal());
        Long userID= iUserService.selectUser(username).getUserId();

       int start=1; //私密导入
        structure="0"; //按目录导入
        try {
            //判断是一层还是二层 0表示按目录导入 否则就按单级别导入
            if(StringUtils.isNotBlank(structure)&& structure=="0"){
                logger.debug("按原目录导入");
                // 按照目录结构导入
                Map<String, Map<String, String>> map = HtmlUtil.parseHtml(htmlFile.getInputStream());
                if(null == map || map.isEmpty()){
                    logger.info("未获取到url连接");
                    return ;
                }
                //迭代所有数据
                for (Entry<String, Map<String, String>> entry : map.entrySet()) {
                    String favoritesName = entry.getKey();
                    //根据名字Userid验证收藏夹是否存在
                    Menu stat=new Menu();
                    stat.setUserId(userID);
                    stat.setMenuName(favoritesName);
//                    List <Menu> namelist=iMenuService.selectByExample(stat);
                    Menu menuklist = iMenuService.selectByMenu(stat);
                    //验证存在的收藏夹是否是最最下级目录
                    List<Menu> listme = null;
                    if (menuklist!=null){

                    Menu menus= new Menu();
                    menus.setUserId(userID);
                    menus.setParentId(menuklist.getMenuId());
                    listme=iMenuService.selectByExample(menus);
                    }
//                    Menu namelists = null;
                    //不存在就创建
                    if(menuklist == null || listme==null){
                        Menu add=new Menu();
                        add.setUserId(userID);
                        add.setMenuName(favoritesName);
                        add.setMenuUrl("/bookmark");
                        add.setMenuIcon("el-icon-s-order");
                        iMenuService.insertSelective(add);
                        //查询添加后返回ID
                        Menu men=new Menu();
                        men.setUserId(userID);
                        men.setMenuName(favoritesName);
                        //刚刚创建的目录信息
//                        namelist= iMenuService.selectByExample(men);
                        menuklist = iMenuService.selectByMenu(men);
                    }
                    //第二个map循环添加  调用importHtml 开始吧书签数据都添加进去
                    System.out.println(menuklist.getMenuId()+"_"+ userID+start+type);

                    importHtml(entry.getValue(), menuklist.getMenuId(), userID,start,type);
                }
            }else{
                Map<String, String> map = HtmlUtil.parseHtmlOne(htmlFile.getInputStream());
                if(null == map || map.isEmpty()){
                    logger.info("未获取到url连接");
                    return ;
                }
                // 全部导入到<导入的书签>收藏夹
                Menu stat=new Menu();
                stat.setUserId(userID);
                stat.setMenuName("导入的书签");
                List <Menu> namelist=iMenuService.selectByExample(stat);

                if(namelist == null || namelist.size() == 0){
                    Menu add=new Menu();
                    add.setUserId(userID);
                    add.setMenuName("导入的书签");
                    add.setMenuUrl("/bookmark");
                    add.setMenuIcon("el-icon-postcard");
                    iMenuService.insertSelective(add);
                    //查询添加后返回ID
                    Menu men=new Menu();
                    men.setUserId(userID);
                    men.setMenuName("导入的书签");
                    //刚刚创建的目录信息
                    namelist= iMenuService.selectByExample(men);

                }
                importHtml(map, namelist.get(0).getMenuId(), userID,start,type);
            }
        }catch (SSLHandshakeException e){
            logger.error("文章解析出错:",e);
        }
        catch (DataIntegrityViolationException e){
            logger.error("导入存储异常:",e);
        }
        catch (HttpStatusException a){
            logger.error("文档解析错误:",a);
        }
        catch (Exception e) {
            logger.error("导入html异常:",e);
        }
    }



    /**
     * 导入收藏文章  书签map  书签目录ID  用户ID 私密公开 type
     */
    public void importHtml(Map<String, String> map,Long favoritesId,Long userId,int start,String type){
        for(Map.Entry<String, String> entry : map.entrySet()){
            try {
                //获取URL后查询最新的URL信息
                Map<String, String> result = HtmlUtil.getCollectFromUrl(entry.getKey());
                String base64_str = "";
                Bookmark collect = new Bookmark();
                //编码
                //collect.setCharset(result.get("charset"));
                if(StringUtils.isBlank(result.get("title"))){
                    collect.setTitle(entry.getValue());
                }else{
                    collect.setTitle(result.get("title"));
                }
                if(StringUtils.isBlank(result.get("description"))){
                    collect.setDescription(collect.getTitle());
                }else{
                    collect.setDescription(result.get("description"));
                }
                collect.setMenuId(favoritesId);
                //0 表示公开显示  1隐藏
                collect.setStart(start);
                collect.setUrl(entry.getKey());
                try {
                    base64_str = Base64.Urlutils(new URL(entry.getKey()));
                  } catch (MalformedURLException e) {
                     e.printStackTrace();
                 }
                collect.setUrls(base64_str);

//                String imgFilePath="https://www.zyymg.com/v2/get.php?url="+entry.getKey();
//                String image= Base64.encodeImageToBase64(new URL(imgFilePath));//将网络图片编码为base64
//                collect.setImage(image);


                collect.setUserid(userId);
                Date datee = new Date();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateStr = format.format(datee);
                collect.setCreateTime(dateStr);
                //使用传入的书签目录ID userID URL 是否删除 查询此目录下 URL是否存在

                Bookmark bookmark=new Bookmark();
                bookmark.setMenuId(favoritesId);
                bookmark.setUrl(entry.getKey());
                bookmark.setUserid(userId);
                bookmark.setIdelete(0);



                Long  counturl= iBookMarkService.countByExample(bookmark);
                if(counturl!=0){
                    logger.info("收藏夹：" + favoritesId + "中已经存在：" + entry.getKey() + "这个文章，不在进行导入操作");
                    continue;
                }
                //添加书签
                iBookMarkService.insertSelective(collect);
//                favoritesService.countFavorites(favoritesId);
            } catch (Exception e) {
                logger.error("导入存储异常：",e);
            }
        }

    }



}
